#include"spi.h"

void spi_init(void)
{
    //开启时钟 
    RCC->APB2ENR|=RCC_APB2ENR_IOPAEN;
    RCC->APB2ENR|=RCC_APB2ENR_IOPCEN;
    RCC->APB2ENR|=RCC_APB2ENR_SPI1EN;

    //配置GPIO PA5 PA7 PC13 通用推挽输出 MODE 11 CNF 00      PA6 浮空输入 MODE 00 CNF 01  
    GPIOA->CRL|=(GPIO_CRL_MODE5|GPIO_CRL_MODE7);
    GPIOA->CRL&=~(GPIO_CRL_CNF5|GPIO_CRL_CNF7);

    GPIOC->CRH|=GPIO_CRH_MODE13;
    GPIOC->CRH&=~GPIO_CRH_CNF13;

    GPIOA->CRL&=~GPIO_CRL_MODE6;
    GPIOA->CRL&=~GPIO_CRL_CNF6_1;
    GPIOA->CRL|=GPIO_CRL_CNF6_0;

    //初始化
    SPI_SCK_LOW;

    SPI_CS_HIGH;

    Delay_us(5);
}

void spi_start(void)
{
    SPI_CS_LOW;
}

void spi_stop(void)
{
    SPI_CS_HIGH;
}

uint8_t spi_swapdata(uint8_t data)
{
    uint8_t rdata;
    for (uint8_t i = 0; i < 8; i++)
    {
        if(data & 0x80)
        {
            SPI_MOSI_HIGH;
        }
        else
        {
            SPI_MOSI_LOW;
        }
        data<<=1;

        SPI_SCK_HIGH;
        rdata<<=1;

        if(SPI_READ)
        {
            rdata|=0x01;
        }
        SPI_SCK_LOW;
        
    }
    return rdata;
    
}
